import { ipcRenderer } from "electron";

let timer = null;
let tryCount = 0;
export const startWatch = () => {
  stopWatch();
  tryCount = 0;
  timer = setInterval(async () => {
    if (tryCount > 4) {
      stopWatch();
      return;
    }
    try {
      const list = await ipcRenderer.invoke("getDeviceListByHdc");
      if (list.length) {
        ipcRenderer.send("freshDeviceList");
        stopWatch();
      } else {
        const list = await ipcRenderer.invoke("getDeviceListByAdb");
        if (list.length) {
          ipcRenderer.send("freshDeviceList");
          stopWatch();
        }
      }
    } catch (err) {
      console.log(err);
    }
    tryCount++;
  }, 500);
};

export const stopWatch = () => {
  if (timer) {
    clearInterval(timer);
    timer = null;
  }
};
